﻿using Aribaccio.Core;
using BDPAutodetect.Mgrcore;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BDPAutodetect.Client
{
    /// <summary>
    /// ParameterSelectDialog.xaml 的交互逻辑
    /// </summary>
    [ObservableObject]
    public partial class ParameterSelectDialog : Window, IDialog<MParameterData>
    {
        /// <summary>
        /// 线程同步更新View
        /// </summary>
        protected readonly TaskScheduler syncContextTask = TaskScheduler.FromCurrentSynchronizationContext();
        /// <summary>
        /// 参数管理实例
        /// </summary>
        protected ParameterManager? ParameterMgr { get; set; }
        /// <summary>
        /// 查询当前从机设备
        /// </summary>
        [ObservableProperty]
        protected MSlave? slaveItem;
        /// <summary>
        /// 查询从机设备集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MSlave> slaveItems = new ObservableCollection<MSlave>();
        /// <summary>
        /// 当前选择参数配置数据
        /// </summary>
        [ObservableProperty]
        protected MParameterData? parameter;
        /// <summary>
        /// 参数配置数据集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MParameterData> parameters = new ObservableCollection<MParameterData>();
        /// <summary>
        /// 界限数据集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MParameterLimitData> parameterLimits = new ObservableCollection<MParameterLimitData>();
        /// <summary>
        /// 返回结果信息
        /// </summary>
        public MParameterData? DialogResultData { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public ParameterSelectDialog(MParameterData? argParameter)
        {
            InitializeComponent();
            this.ParameterMgr = ContainerManager.Instance.GetContainerServiceRequired<ParameterManager>();
            this.DataContext = this;
            this.SlaveItem = argParameter?.Slave;
            this.Parameter = argParameter;
        }

        /// <summary>
        /// 页面初始化加载事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteLoaded()
        {
            if (this.ParameterMgr == null) return;
            //初始化从机设备数据
            var slaves = this.ParameterMgr.GetSlaves();
            foreach (var item in slaves.OrderBy(v => v.ID))
            {
                if (item.ID <= 0) continue;
                this.SlaveItems.Add(item);
            }
            if (this.SlaveItem == null)
            {
                this.SlaveItem = this.SlaveItems.First();
            }
            //初始化查询参数列表
            var resultTask = this.QueryParameter(this.SlaveItem);
            await resultTask.ConfigureAwait(false);
            //初始化查询参数界限数据
            resultTask = this.QueryParameterLimit(this.Parameter);
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 从机设备选择改变指令事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteSlaveSelectionChanged()
        {
            var resultTask = this.QueryParameter(this.SlaveItem);
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 参数选择改变指令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteParameterSelectionChanged()
        {
            var resultTask = this.QueryParameterLimit(this.Parameter);
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 确认选择事件
        /// </summary>
        [RelayCommand]
        public void ExecuteConfirmOk()
        {
            this.DialogResult = true;
            this.DialogResultData = this.Parameter;
            this.Close();
        }

        /// <summary>
        /// 取消事件
        /// </summary>
        [RelayCommand]
        public void ExecuteConfirmCancel()
        {
            this.DialogResult = false;
            this.Close();
        }

        /// <summary>
        /// 查询参数数据
        /// </summary>
        /// <param name="argSlaveItem">从机设备实例</param>
        protected async Task QueryParameter(MSlave? argSlaveItem)
        {
            await Task.Factory.StartNew(() =>
            {
                if (argSlaveItem == null) return;
                this.Parameters.Clear();
                var datas = this.ParameterMgr?.GetParameters(argSlaveItem);
                if (datas == null || datas.Count <= 0) return;

                foreach (var item in datas)
                {
                    this.Parameters.Add(item);
                }
                //绑定参数
                if (this.Parameter == null || (this.Parameter != null && !this.Parameters.Contains(this.Parameter)))
                {
                    this.Parameter = this.Parameters[0];
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, this.syncContextTask);
        }

        /// <summary>
        /// 查询参数界限数据
        /// </summary>
        /// <returns></returns>
        protected async Task QueryParameterLimit(MParameterData? argParameter)
        {
            await Task.Factory.StartNew(() =>
            {
                this.ParameterLimits.Clear();
                if (argParameter == null) return;
                foreach (var item in argParameter.Limits.OrderBy(v => v.ID))
                {
                    this.ParameterLimits.Add(item);
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, this.syncContextTask);
        }
    }
}
